package com.ruoyi.project.system.controller

import com.ruoyi.common.constant.Constants
import com.ruoyi.common.utils.SecurityUtils
import com.ruoyi.framework.security.LoginBody
import com.ruoyi.framework.security.service.SysLoginService
import com.ruoyi.framework.security.service.SysPermissionService
import com.ruoyi.framework.web.domain.AjaxResult
import com.ruoyi.project.system.service.ISysMenuService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RestController

/**
 * 登录验证
 *
 * @author ruoyi
 */
@RestController
open class SysLoginController {
    @Autowired
    private val loginService: SysLoginService? = null

    @Autowired
    private val menuService: ISysMenuService? = null

    @Autowired
    private val permissionService: SysPermissionService? = null

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    fun login(@RequestBody loginBody: LoginBody): AjaxResult {
        val ajax: AjaxResult = AjaxResult.success()
        // 生成令牌
        val token = loginService!!.login(
            loginBody.username, loginBody.password, loginBody.code,
            loginBody.uuid
        )
        ajax[Constants.TOKEN] = token
        return ajax
    }// 角色集合
    // 权限集合
    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    fun getInfo(): AjaxResult {
        val user = SecurityUtils.getLoginUser().user!!
        // 角色集合
        val roles = permissionService!!.getRolePermission(user)
        // 权限集合
        val permissions = permissionService.getMenuPermission(user)
        val ajax: AjaxResult = AjaxResult.success()
        ajax["user"] = user
        ajax["roles"] = roles
        ajax["permissions"] = permissions
        return ajax
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getRouters")
    fun getRouters(): AjaxResult {
        val userId = SecurityUtils.getUserId()
        val menus = menuService!!.selectMenuTreeByUserId(userId)
        return AjaxResult.success(menuService.buildMenus(menus))
    }
}
